<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Request;
use App\Models\User;
use App\Models\Topic;
use App\Models\Message;
use App\Logic\UserLogic;

use App\Http\Requests\Password;
use App\Http\Resources\MessageResource;

class UserController extends Controller
{

    protected $userMdl;

    public function __construct(User $user)
    {
        $this->userMdl = $user;
    }

    /**
     * 修改密码
     * User: 920078259@qq.com
     * @param $userId
     * @param Password $request
     * @param UserLogic $userLogic
     * @return \Illuminate\Http\JsonResponse
     */
    public function password($userId, Password $request, UserLogic $userLogic)
    {
        // 验证数据
        $validata = $request->validated();
        if ($validata['password'] !== $validata['confirm_password']) {
            return $this->json([], '新密码和确认密码不一致', 400);
        }

        // 验证旧密码
        $userInfo = $this->userMdl->find($userId);
        $result = $userLogic->checkPassword($userInfo['email'], $validata['old_password']);
        if ($result['code'] == 0) {
            return $this->json([], $result['msg'], 400);
        }

        // 修改密码
        $userInfo->password = Hash::make($validata['password']);
        $userInfo->save();

        return $this->json([], '密码修改成功，请重新登录');
    }

    /**
     * 用户发的帖
     * User: 920078259@qq.com
     * @param $userId
     * @param Topic $topic
     * @return \Illuminate\Http\JsonResponse
     */
    public function userTopic($userId, Topic $topic)
    {

        $page = Request::input('page', 1);
        $perPage = Request::input('per_page', 10);
        $list = $topic->getPaginate(['user_id' => $userId], [], $topic->select, $page, $perPage, ['id', 'desc']);
        return $this->json($list);
    }

    /**
     * 我的消息
     * User: 920078259@qq.com
     * @param $userId
     * @param Message $message
     * @param MessageResource $messageResource
     * @return \Illuminate\Http\JsonResponse
     */
    public function message($userId, Message $message, MessageResource $messageResource)
    {
        $page = Request::input('page', 1);
        $perPage = Request::input('per_page', 10);
        $data = $message->getPaginate(['user_id' => $userId, 'is_read' => 0], ['topic', 'fromUser'], ['*'], $page, $perPage);

        return $this->json($messageResource->formatArray($data));
    }

    /**
     * 设置消息成已读 单条|所有
     * User: 920078259@qq.com
     * @param null $id
     * @param Message $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function isRead($id = null, Message $message)
    {

        $user_id = 2;
        if ($id) {
            $where = ['id' => $id, 'user_id' => $user_id];
        } else {
            $where = ['user_id' => $user_id];
        }
        $message->where($where)->update(['is_read' => 1]);

        return $this->json();
    }




}
